package breeze.tool.life.utils;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import breeze.tool.life.App;
import breeze.tool.life.module.WeatherNowBean;
import brz.breeze.service_utils.BExceptionCatcher;
import brz.breeze.web_utils.BWebUtils;
import com.google.gson.Gson;
import android.content.res.AssetManager;
import java.io.IOException;
import breeze.tool.life.module.Weather3DBean;

public class AppWeatherUtils {
    
    /*
	*@author BREEZE
	*@date 2021-11-28 10:54:11
    */
    public static final String TAG = "AppWeatherUtils";
    
    private static final String NOW_API = "https://devapi.qweather.com/v7/weather/now?location={location}&key=c7a77200a5c746918803cb936ca374d3";

	private static final String _3D_API = "https://devapi.qweather.com/v7/weather/3d?location={location}&key=c7a77200a5c746918803cb936ca374d3";
	
	private static SharedPreferences pm;
	
	static{
		pm = PreferenceManager.getDefaultSharedPreferences(App.getContext());
	}
	
	
	public static WeatherNowBean getWeatherNow(){
		try{
			String result = BWebUtils.getWebContent(NOW_API.replace("{location}",pm.getString("city_id","101270101")));
			if(null!=result||!result.isEmpty()){
				Gson gson = new Gson();
				WeatherNowBean bean = gson.fromJson(result,WeatherNowBean.class);
				return bean;
			}
			return null;
		}catch(Exception e){
			BExceptionCatcher.e(App.getContext(),e);
			return null;
		}
	}
	
	public static void updateWidget(Context context){
		Intent intent = new Intent("android.appwidget.action.APPWIDGET_UPDATE");
		context.sendBroadcast(intent);
	}
	
	public static Bitmap getWeatherIcon(Context context,String icon){
		AssetManager am = context.getAssets();
		try {
			return BitmapFactory.decodeStream(am.open("weathericon/" + icon + ".png"));
		} catch (IOException e) {
			return getWeatherIcon(context,"999");
		}
	}
	
	public static Weather3DBean getWeather3DBean(){
		try {
			String result = BWebUtils.getWebContent(_3D_API.replace("{location}", pm.getString("city_id", "101270101")));
			if(null!=result||!result.isEmpty()){
				Gson gson = new Gson();
				Weather3DBean bean = gson.fromJson(result,Weather3DBean.class);
				return bean;
			}
			return null;
		} catch (IOException e) {
			return null;
		}
	}
    
}
